package com.xysoft.framework.event;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.persister.entity.EntityPersister;

public class HibernateUtils {
	static Object loadOldEntity(final Object entity, Session session) {
		
		String entityName = ((SessionImplementor) session).bestGuessEntityName(entity);
		EntityPersister persister = ((SessionImplementor) session).getFactory().getEntityPersister(entityName);
		Serializable identifier = persister.getIdentifier(entity, ((SessionImplementor) session));
		PersistenceContext context = ((SessionImplementor) session).getPersistenceContext();
		EntityEntry entityEntry = context.getEntry(entity);

		Object instance = null;
		if (entityEntry == null) {
			instance = entity;
		} else {
			instance = persister.instantiate(identifier, ((SessionImplementor) session));
			persister.setPropertyValues(instance, entityEntry.getLoadedState());
		}
		return instance;
	}
}
